// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: hyuan

#pragma once

#include <cstdio>
#include <memory>
#include <set>
#include <string>

#include <rapidjson/document.h>

#include "coin2/exchange/base/order/order.h"
#include "coin2/exchange/phemex/symbology/product.h"
#include "coin2/exchange/phemex_base/api_util/rate_tracker.h"

namespace coin2::exchange::phemex::order_v1 {

class PhemexParser : public base::order::BaseParser {
 public:
  using RateLimitInfo = coin2::exchange::phemex::api_util::RateLimitInfo;

 public:
  const ParseResult& ParseRawMessage(const RawMessage& msg) override;
  AccountBalance ParseBalance(const JsonValue& doc) override;

 private:
  void ParseRestAccountBalance();
  void ParseRestOpenOrders();
  void ParseRestHistoryOrders();
  void ParseRestFillOrders();
  void ParseRestDeposit();
  void ParseRestWithdraw();
  void ParseSubmitResponse();
  void ParseCancelResponse();
  void ParseWsMessage();
  bool ParseWsOpenOrders(const JsonValue& open_orders);
  bool ParseWsClosedOrders(const JsonValue& closed_orders);
  bool ParseWsFillOrders(const JsonValue& fill_orders);
  void ParseWsOrderInfoList(const JsonDocument& document);
  void ParseWsWalletInfoList(const JsonDocument& document);

  void ParseRestTransferFutures(const std::string&);
  void ParseRestTransferSpot(const std::string&);

  void ParseHeader(const std::shared_ptr<AsioHttpContext>&);

 private:
  std::string user_id;
  std::map<std::string, std::string> transfer_map_;
  RateLimitInfo rate_limit_spotorder_{500};
  RateLimitInfo enable_time_spotorder_{0};
  RateLimitInfo rate_limit_others_{100};
  RateLimitInfo enable_time_others_{0};

  std::set<std::string> transfer_init_set_;
  std::map<std::string, std::string> transfer_record_map_;

  std::string master_account_id_{"2060211"};  // phemexc prestoinv0
};

}  // namespace coin2::exchange::phemex::order_v1
